/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径集合
 *@param - sign:后台接口返回的签名信息
 *@param - successc:成功回调
 *@param - failc:失败回调
 */
const uploadFile = function (filePath, sign, successc, failc) {
  if (!filePath) {
    wx.showModal({
      title: '图片错误',
      content: '请重试',
      showCancel: false
    });
    return;
  }
  // 图片名称，可自行定义，这里使用当前文件名+时间戳+150以内的随机数 //+ '.png'
  function randomString(len) {
    len = len || 32;
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    const maxPos = chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }
  // sign.dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
  const aliyunFileKey = `${sign.dir}/${randomString(36)}`;
  const aliyunServerURL = sign.host + '/'; // OSS地址需要https
  const accessid = sign.accessid;
  const policyBase64 = sign.policy;
  const signature = sign.signature; // 获取签名
  wx.uploadFile({
    url: aliyunServerURL, // 开发者服务器 url aliyunServerURL /https://static.wmeimob.com
    filePath: filePath, // 需要上传的图片路径
    name: 'file', // 必须填写为file
    formData: {
      key: aliyunFileKey,
      policy: policyBase64,
      OSSAccessKeyId: accessid,
      signature: signature,
      success_action_status: '200'
    },
    success: function (res) {
      if (res.statusCode !== 200) {
        failc(new Error('上传错误:' + JSON.stringify(res)));
        return;
      }
      successc(aliyunServerURL + aliyunFileKey);
    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      failc(err);
    }
  });
};
export default uploadFile;
